// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()

  let isSelf = event.isSelf || false
  let db = cloud.database();
  let today = new Date()
  let sundayTimeStamp = today - today.getDay() * 24 * 3600 * 1000
  let sundayString = new Date(sundayTimeStamp).toLocaleDateString().replace(/\//g, '-')
  let res;
  const _ = db.command
  try {
    let r = await db.collection("tb_schedule").where({
      date: _.gt(sundayString),
      _openid: wxContext.OPENID
    }).get()
    res = {}
    let list = r.data;
    let courses = ["maths", "chinese", "english", "physical", "chemistry", "history", "politics"]
    courses.forEach(key => {
      res[key] = list.reduce((p, c) => {
        let courseObj = isSelf ? c['self'] : c
        if (!courseObj) return p
        return p + (courseObj[key] && courseObj[key].duration ? courseObj[key].duration : 0)
      }, 0)
    })
  } catch (e) {
    console.log('error')
  }
  return res;
}